import { useState } from 'react'
import './EventHandling.css'

// 基本点击事件
function ClickExample() {
  const [count, setCount] = useState(0)
  const [message, setMessage] = useState('')

  const handleClick = () => {
    setCount(count + 1)
    setMessage(`按钮被点击了 ${count + 1} 次`)
  }

  const handleReset = () => {
    setCount(0)
    setMessage('计数器已重置')
  }

  return (
    <div className="click-example">
      <h3>点击事件</h3>
      <button onClick={handleClick}>点击我</button>
      <button onClick={handleReset}>重置</button>
      <p>点击次数: {count}</p>
      <p>{message}</p>
    </div>
  )
}

// 表单事件
function FormExample() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    message: ''
  })

  const handleChange = (e) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
  }

  const handleSubmit = (e) => {
    e.preventDefault() // 阻止表单默认提交行为
    alert(`表单提交: ${JSON.stringify(formData, null, 2)}`)
  }

  const handleReset = () => {
    setFormData({ name: '', email: '', message: '' })
  }

  return (
    <div className="form-example">
      <h3>表单事件</h3>
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label>姓名:</label>
          <input
            type="text"
            name="name"
            value={formData.name}
            onChange={handleChange}
          />
        </div>
        
        <div className="form-group">
          <label>邮箱:</label>
          <input
            type="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
          />
        </div>
        
        <div className="form-group">
          <label>消息:</label>
          <textarea
            name="message"
            value={formData.message}
            onChange={handleChange}
            rows="3"
          />
        </div>
        
        <div className="form-buttons">
          <button type="submit">提交</button>
          <button type="button" onClick={handleReset}>重置</button>
        </div>
      </form>
      
      <div className="form-data">
        <h4>当前表单数据:</h4>
        <pre>{JSON.stringify(formData, null, 2)}</pre>
      </div>
    </div>
  )
}

// 鼠标事件
function MouseExample() {
  const [position, setPosition] = useState({ x: 0, y: 0 })
  const [isHovering, setIsHovering] = useState(false)
  const [clickCount, setClickCount] = useState(0)

  const handleMouseMove = (e) => {
    setPosition({ x: e.clientX, y: e.clientY })
  }

  const handleMouseEnter = () => {
    setIsHovering(true)
  }

  const handleMouseLeave = () => {
    setIsHovering(false)
  }

  const handleDoubleClick = () => {
    setClickCount(prev => prev + 1)
  }

  return (
    <div className="mouse-example">
      <h3>鼠标事件</h3>
      
      <div 
        className="mouse-area"
        onMouseMove={handleMouseMove}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
        onDoubleClick={handleDoubleClick}
      >
        <p>在这个区域移动鼠标</p>
        <p>双击增加计数</p>
        <p>位置: ({position.x}, {position.y})</p>
        <p>悬停状态: {isHovering ? '是' : '否'}</p>
        <p>双击次数: {clickCount}</p>
      </div>
    </div>
  )
}

// 键盘事件
function KeyboardExample() {
  const [keyPressed, setKeyPressed] = useState('')
  const [keyHistory, setKeyHistory] = useState([])
  const [inputValue, setInputValue] = useState('')

  const handleKeyDown = (e) => {
    setKeyPressed(`按下: ${e.key} (代码: ${e.keyCode})`)
  }

  const handleKeyUp = (e) => {
    setKeyHistory(prev => [...prev.slice(-4), e.key])
  }

  const handleInputChange = (e) => {
    setInputValue(e.target.value)
  }

  const handleSpecialKeys = (e) => {
    if (e.key === 'Enter') {
      alert('你按了回车键!')
    } else if (e.key === 'Escape') {
      setInputValue('')
    }
  }

  return (
    <div className="keyboard-example">
      <h3>键盘事件</h3>
      
      <div className="keyboard-area">
        <input
          type="text"
          value={inputValue}
          onChange={handleInputChange}
          onKeyDown={handleKeyDown}
          onKeyUp={handleKeyUp}
          onKeyPress={handleSpecialKeys}
          placeholder="在这里输入文字..."
        />
        
        <p>最后按下的键: {keyPressed}</p>
        
        <div className="key-history">
          <h4>按键历史:</h4>
          <ul>
            {keyHistory.map((key, index) => (
              <li key={index}>{key}</li>
            ))}
          </ul>
        </div>
        
        <div className="special-keys">
          <h4>特殊键:</h4>
          <p>按 Enter 键触发提示</p>
          <p>按 Escape 键清空输入</p>
        </div>
      </div>
    </div>
  )
}

// 事件对象和阻止默认行为
function EventObjectExample() {
  const [linkClicked, setLinkClicked] = useState(false)
  const [contextMenu, setContextMenu] = useState(false)

  const handleLinkClick = (e) => {
    e.preventDefault() // 阻止链接默认跳转行为
    setLinkClicked(true)
    setTimeout(() => setLinkClicked(false), 2000)
  }

  const handleContextMenu = (e) => {
    e.preventDefault() // 阻止右键菜单
    setContextMenu(true)
    setTimeout(() => setContextMenu(false), 2000)
  }

  const handleEventInfo = (e) => {
    console.log('事件对象:', e)
    console.log('事件类型:', e.type)
    console.log('目标元素:', e.target)
    console.log('当前元素:', e.currentTarget)
  }

  return (
    <div className="event-object-example">
      <h3>事件对象和阻止默认行为</h3>
      
      <div className="event-demos">
        <div className="demo-item">
          <h4>阻止链接跳转:</h4>
          <a 
            href="https://www.example.com" 
            onClick={handleLinkClick}
            className="custom-link"
          >
            点击这个链接 (不会跳转)
          </a>
          {linkClicked && <p className="success-message">链接被点击了，但没有跳转!</p>}
        </div>
        
        <div className="demo-item">
          <h4>阻止右键菜单:</h4>
          <div 
            className="context-area"
            onContextMenu={handleContextMenu}
          >
            在这个区域右键点击
          </div>
          {contextMenu && <p className="success-message">右键菜单被阻止了!</p>}
        </div>
        
        <div className="demo-item">
          <h4>事件信息:</h4>
          <button onClick={handleEventInfo}>
            点击查看控制台事件信息
          </button>
        </div>
      </div>
    </div>
  )
}

// 事件委托
function EventDelegationExample() {
  const [items, setItems] = useState([
    { id: 1, name: '项目 1', active: false },
    { id: 2, name: '项目 2', active: false },
    { id: 3, name: '项目 3', active: false }
  ])

  const handleItemClick = (e) => {
    // 事件委托：检查点击的是否是按钮
    if (e.target.tagName === 'BUTTON') {
      const itemId = parseInt(e.target.dataset.id)
      setItems(prev => prev.map(item => 
        item.id === itemId 
          ? { ...item, active: !item.active }
          : item
      ))
    }
  }

  const addItem = () => {
    const newId = Math.max(...items.map(item => item.id)) + 1
    setItems(prev => [...prev, { id: newId, name: `项目 ${newId}`, active: false }])
  }

  return (
    <div className="event-delegation-example">
      <h3>事件委托</h3>
      <p>使用事件委托处理多个相似元素的事件</p>
      
      <button onClick={addItem} className="add-button">添加项目</button>
      
      <div className="item-list" onClick={handleItemClick}>
        {items.map(item => (
          <div key={item.id} className={`item ${item.active ? 'active' : ''}`}>
            <span>{item.name}</span>
            <button data-id={item.id}>
              {item.active ? '停用' : '激活'}
            </button>
          </div>
        ))}
      </div>
    </div>
  )
}

// 自定义事件处理
function CustomEventExample() {
  const [customEvents, setCustomEvents] = useState([])

  const addCustomEvent = (eventName, data) => {
    const event = {
      id: Date.now(),
      name: eventName,
      data: data,
      timestamp: new Date().toLocaleTimeString()
    }
    setCustomEvents(prev => [event, ...prev.slice(0, 4)]) // 只保留最近5个事件
  }

  const handleCustomAction = (action) => {
    // 模拟自定义事件
    addCustomEvent('自定义操作', { action, user: '当前用户' })
  }

  const clearEvents = () => {
    setCustomEvents([])
  }

  return (
    <div className="custom-event-example">
      <h3>自定义事件处理</h3>
      
      <div className="action-buttons">
        <button onClick={() => handleCustomAction('保存数据')}>保存数据</button>
        <button onClick={() => handleCustomAction('发送邮件')}>发送邮件</button>
        <button onClick={() => handleCustomAction('生成报告')}>生成报告</button>
        <button onClick={clearEvents}>清空事件</button>
      </div>
      
      <div className="event-log">
        <h4>事件日志:</h4>
        {customEvents.length === 0 ? (
          <p>暂无事件记录</p>
        ) : (
          <ul>
            {customEvents.map(event => (
              <li key={event.id}>
                <span className="event-time">{event.timestamp}</span>
                <span className="event-name">{event.name}</span>
                <span className="event-data">{JSON.stringify(event.data)}</span>
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  )
}

function EventHandling() {
  return (
    <div className="example-page">
      <div className="example-header">
        <h1>事件处理</h1>
        <p>学习 React 中的事件处理机制，包括各种事件类型和最佳实践</p>
      </div>

      <div className="example-section">
        <h2>1. 基本点击事件</h2>
        <p>最常见的事件处理方式：</p>
        
        <div className="code-block">
{`function ClickExample() {
  const [count, setCount] = useState(0)

  const handleClick = () => {
    setCount(count + 1)
  }

  return (
    <div>
      <button onClick={handleClick}>点击我</button>
      <p>点击次数: {count}</p>
    </div>
  )
}`}
        </div>

        <div className="demo-container">
          <div className="demo-title">点击事件示例：</div>
          <div className="demo-content">
            <ClickExample />
          </div>
        </div>
      </div>

      <div className="example-section">
        <h2>2. 表单事件</h2>
        <p>处理表单输入和提交：</p>
        
        <div className="demo-container">
          <div className="demo-title">表单事件示例：</div>
          <div className="demo-content">
            <FormExample />
          </div>
        </div>
      </div>

      <div className="example-section">
        <h2>3. 鼠标事件</h2>
        <p>处理鼠标移动、悬停、点击等事件：</p>
        
        <div className="demo-container">
          <div className="demo-title">鼠标事件示例：</div>
          <div className="demo-content">
            <MouseExample />
          </div>
        </div>
      </div>

      <div className="example-section">
        <h2>4. 键盘事件</h2>
        <p>处理键盘按键事件：</p>
        
        <div className="demo-container">
          <div className="demo-title">键盘事件示例：</div>
          <div className="demo-content">
            <KeyboardExample />
          </div>
        </div>
      </div>

      <div className="example-section">
        <h2>5. 事件对象和阻止默认行为</h2>
        <p>了解事件对象和如何阻止默认行为：</p>
        
        <div className="demo-container">
          <div className="demo-title">事件对象示例：</div>
          <div className="demo-content">
            <EventObjectExample />
          </div>
        </div>
      </div>

      <div className="example-section">
        <h2>6. 事件委托</h2>
        <p>使用事件委托优化性能：</p>
        
        <div className="code-block">
{`// 事件委托示例
function ItemList({ items }) {
  const handleItemClick = (e) => {
    if (e.target.tagName === 'BUTTON') {
      const itemId = parseInt(e.target.dataset.id)
      // 处理点击事件
    }
  }

  return (
    <div onClick={handleItemClick}>
      {items.map(item => (
        <div key={item.id}>
          <span>{item.name}</span>
          <button data-id={item.id}>操作</button>
        </div>
      ))}
    </div>
  )
}`}
        </div>

        <div className="demo-container">
          <div className="demo-title">事件委托示例：</div>
          <div className="demo-content">
            <EventDelegationExample />
          </div>
        </div>
      </div>

      <div className="example-section">
        <h2>7. 自定义事件处理</h2>
        <p>创建自定义事件处理逻辑：</p>
        
        <div className="demo-container">
          <div className="demo-title">自定义事件示例：</div>
          <div className="demo-content">
            <CustomEventExample />
          </div>
        </div>
      </div>

      <div className="tip">
        <strong>事件处理最佳实践：</strong>
        <ul>
          <li>使用驼峰命名法命名事件处理器 (onClick, onChange 等)</li>
          <li>传递事件处理函数而不是字符串 (onClick={handleClick} 而不是 onClick="handleClick()")</li>
          <li>使用 preventDefault() 阻止默认行为</li>
          <li>使用 stopPropagation() 阻止事件冒泡</li>
          <li>对于大量相似元素，考虑使用事件委托</li>
          <li>在事件处理器中使用函数式更新避免状态问题</li>
        </ul>
      </div>
    </div>
  )
}

export default EventHandling